

package cn.shengchao.examstar.distribute.ohs.local.appservice;

import cn.hutool.core.collection.CollUtil;
import cn.shengchao.examstar.rpc.base.TransResult;
import cn.shengchao.examstar.rpc.distribute.cs.UserCs;
import cn.shengchao.examstar.distribute.infrastrure.po.*;
import cn.shengchao.examstar.distribute.infrastrure.service.*;
import cn.shengchao.examstar.rpc.distribute.enums.DistributeContentRoleEnum;
import cn.shengchao.examstar.rpc.distribute.enums.DistributeDataStatusEnum;
import cn.shengchao.examstar.distribute.exception.DistributeException;
import cn.shengchao.examstar.distribute.model.DistributeNodeRoleChainCreator;
import cn.shengchao.examstar.distribute.model.DistributeNodeRoleChainExistModel;
import cn.shengchao.examstar.rpc.distribute.enums.DistributeSaleRoleEnum;
import cn.shengchao.examstar.rpc.distribute.enums.DistributeTypeEnum;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @program: examstarapi
 * @description: 现有分销链用户模型的加载器
 * @author: Xiong weiqiang
 * @create: 2025-03-26 13:52
 */
@Component
@RequiredArgsConstructor
public class DistributeNodeRoleChainExistLoader {
    private final DistributeNodeRoleService distributeNodeRoleService;
    private final DistributeNodeInfoService distributeNodeInfoService;
    private final DistributeNodeRoleChainService distributeNodeRoleChainService;
    private final DistributeDeptUserRoleBindService distributeDeptUserRoleBindService;
    private final DistributeDeptInfoService distributeDeptInfoService;

    /**
     * method : checkSaleNodeCreate
     * description :
     * 
     * @param userId       \{@link Long \}
     * @param saleRoleEnum \{@link DistributeSaleRoleEnum \}
     * @return : cn.shengchao.examstar.base.TransResult
     * @author : Xiong weiqiang
     * @CreateDate : 2025-03-30 16:28:04
     * 
     * @Reviewed :
     * @UpdateLog : Name Date Reason/Contents
     *            ---------------------------------------
     *            **** **** ****
     *
     */
    public TransResult<DistributeNodeRoleChainExistModel> checkSaleNodeCreate(Long userId,
                                                                              DistributeSaleRoleEnum saleRoleEnum) {
        DistributeNodeRoleChainExistModel existModel = loadModelByUserId(userId, DistributeTypeEnum.TYPE_SALE
            .getType());
        TransResult<DistributeNodeRoleChainExistModel> transResult = TransResult.success(existModel, "0");
        if (existModel.getDistributeNodeInfo() == null) {
            //如果是普通用户，直接返回成功
            return transResult;
        }
        switch (saleRoleEnum) {
            case DistributeSaleRoleEnum.ROLE_DSPD -> {
                if (DistributeSaleRoleEnum.ROLE_MKMG.getCode()
                    .equals(existModel.getDistributeNodeInfo().getDistributeRoleCode())) {
                    return TransResult.fail("用户已经存在市场经理角色，不能重复创建");
                }
                if (DistributeSaleRoleEnum.ROLE_DSPD.getCode()
                    .equals(existModel.getDistributeNodeInfo().getDistributeRoleCode())) {
                    return TransResult.fail("用户已经存在加盟商角色，不能重复创建");
                }
            }
            case DistributeSaleRoleEnum.ROLE_DSPD_EMP -> {
                return TransResult.fail("用户已经存在其他角色，不能创建员工");
            }
            case DistributeSaleRoleEnum.ROLE_SLMB -> {
                if (!DistributeSaleRoleEnum.ROLE_DSPD_EMP.getCode()
                    .equals(existModel.getDistributeNodeInfo().getDistributeRoleCode())) {
                    return TransResult.fail("用户已经存在其他分销角色，不能重复创建会员");
                } else {
                    transResult.setMessage("1");
                }
            }
            default -> {
                return TransResult.fail("已经存在分销角色，不支持建立分销用户角色");
            }
        }
        return transResult;
    }

    public TransResult<DistributeNodeRoleChainExistModel> checkContentNodeCreate(Long userId,
                                                                                 DistributeContentRoleEnum contentRoleEnum) {
        DistributeNodeRoleChainExistModel existModel = loadModelByUserIdByDeptChain(userId, DistributeTypeEnum.TYPE_CTPD);
        TransResult<DistributeNodeRoleChainExistModel> transResult = TransResult.success(existModel, "0");
        if (existModel.getDistributeNodeInfo() == null) {
            //如果是普通用户，直接返回成功
            return transResult;
        }
        switch (contentRoleEnum) {
            case DistributeContentRoleEnum.ROLE_CTPD -> {
                if (DistributeContentRoleEnum.ROLE_CTPD.getCode()
                    .equals(existModel.getDistributeNodeInfo().getDistributeRoleCode())) {
                    return TransResult.fail("用户已经存在内容分销商角色，不能重复创建");
                }
            }
            case DistributeContentRoleEnum.ROLE_CTPD_EMP -> {
                return TransResult.fail("用户已经存在其他角色，不能创建员工");
            }

            default -> {
                return TransResult.fail("不支持的内容分销用户角色");
            }
        }
        return transResult;
    }

    /**
     * method : loadModelByUserIdByDeptChain
     * description :分销体系用户的模型，必须有且只有一条生效的节点，角色，链记录,每次修改现存用户用这个方法加载，顺便检查用户链
     *
     * @param userId             \{@link Long \} 分销体系用户id
     * @param distributeTypeEnum \{@link DistributeTypeEnum \} 分销体系用户id
     * @return : cn.shengchao.examstar.distribute.model.DistributeNodeRoleChainExistModel
     * @author : Xiong weiqiang
     * @CreateDate : 2025-03-26 14:05:06
     *
     * @Reviewed :
     * @UpdateLog : Name Date Reason/Contents
     *            ---------------------------------------
     *            **** **** ****
     *
     */
    public DistributeNodeRoleChainExistModel loadModelByUserIdByDeptChain(Long userId,
                                                                          DistributeTypeEnum distributeTypeEnum) throws DistributeException {
        DistributeNodeRoleChainExistModel distributeNodeRoleChainExistModel = new DistributeNodeRoleChainExistModel();
        List<DistributeNodeInfo> userNodes = distributeNodeInfoService.list(Wrappers
            .lambdaQuery(DistributeNodeInfo.class)
            .eq(DistributeNodeInfo::getDistributeType, distributeTypeEnum.getType())
            .eq(DistributeNodeInfo::getUserId, userId)
            .eq(DistributeNodeInfo::getDataStatus, DistributeDataStatusEnum.STATUS_CURT.getStatus()));

        if (CollUtil.isNotEmpty(userNodes) && userNodes.size() > 1) {
            throw new DistributeException("加载现存分销用户错误：本人节点数量:" + userNodes.size());
        }
        //如果用户节点为空，返回空模型，不必再检查了
        if (CollUtil.isEmpty(userNodes)) {
            //返回空模型
            return distributeNodeRoleChainExistModel;
        }
        distributeNodeRoleChainExistModel.setDistributeNodeInfo(userNodes.getFirst());
        DistributeNodeRole distributeNodeRole = distributeNodeRoleService.getById(userNodes.getFirst()
            .getDistributeUserRoleId());
        if (distributeNodeRole == null || DistributeDataStatusEnum.STATUS_CURT.getStatus() != distributeNodeRole
            .getDataStatus()) {
            throw new DistributeException("加载现存分销用户错误：本人角色数据缺失" + (CollUtil.isNotEmpty(userNodes)
                ? userNodes.size()
                : 0));
        }
        distributeNodeRoleChainExistModel.setDistributeNodeRole(distributeNodeRole);
        Long distributeDeptId = distributeDeptUserRoleBindService.getDeptBindIdForUser(userId, distributeTypeEnum);
        if (distributeDeptId == null) {
            throw new DistributeException("加载现存分销用户错误：用户绑定部门id数据缺失");
        }
        DistributeDeptInfo distributeDeptInfo = distributeDeptInfoService.getOne(Wrappers.lambdaQuery(DistributeDeptInfo.class)
                .eq(DistributeDeptInfo::getDistributeType, distributeTypeEnum.getType())
                .eq(DistributeDeptInfo::getDeptId, distributeDeptId).eq(DistributeDeptInfo::getDataStatus,DistributeDataStatusEnum.STATUS_CURT.getStatus())
        );
                //distributeDeptInfoService.getById(distributeDeptId);
        if (distributeDeptInfo == null) {
            throw new DistributeException("加载现存分销用户错误：用户部门数据缺失，用户id"+userId+"distributeDeptId:"+distributeDeptId);
        }

        distributeNodeRoleChainExistModel.setDistributeDeptInfo(distributeDeptInfo);
        DistributeDeptUserRoleBind distributeDeptUserRoleBind = distributeDeptUserRoleBindService.getOne(Wrappers.lambdaQuery(DistributeDeptUserRoleBind.class)
                .eq(DistributeDeptUserRoleBind::getUserId, userId)
                .eq(DistributeDeptUserRoleBind::getDistributeType, distributeTypeEnum.getType())
                .eq(DistributeDeptUserRoleBind::getDataStatus,DistributeDataStatusEnum.STATUS_CURT.getStatus())
        );
        distributeNodeRoleChainExistModel.setDistributeDeptUserRoleBind(distributeDeptUserRoleBind);
        Long upLevelUserId = null;
        //链跟部门管理者的关系是保持一致的。
        //如果用户id和部门用户拥有者id相等，则上级用户为上级节点，如果不是，那就上级是部门的拥有者（加盟商才拥有部门）
        if (userId.equals(distributeDeptInfo.getDeptOwnerId())) {
            upLevelUserId = distributeDeptInfo.getUpLevelUserId();
        } else {
            upLevelUserId = distributeDeptInfo.getDeptOwnerId();
        }
        DistributeNodeInfo upLevelNode = null;
        if (UserCs.PLATFORM_USER_ID.equals(upLevelUserId)) {
            //平台节点
            upLevelNode = DistributeNodeRoleChainCreator.buildPlatformNodeInfo();
        } else {
            upLevelNode = distributeNodeInfoService.getNodeInfoForUser(upLevelUserId, distributeTypeEnum);
        }

        if (upLevelNode == null) {
            throw new DistributeException("加载现存分销用户错误：上级节点找不到" + upLevelUserId);
        } else {
            distributeNodeRoleChainExistModel.setUpLevelNodeInfo(upLevelNode);
        }
        DistributeNodeRoleChain distributeNodeRoleChain = distributeNodeRoleChainService.getOne(Wrappers.lambdaQuery(DistributeNodeRoleChain.class)
                .eq(DistributeNodeRoleChain::getDistributeNodeId, distributeNodeRoleChainExistModel.getDistributeNodeInfo().getId())
                .eq(DistributeNodeRoleChain::getDataStatus,DistributeDataStatusEnum.STATUS_CURT.getStatus())
        );
        if (!upLevelNode.getId().equals(distributeNodeRoleChain.getUpLevelNodeId())) {
            throw new DistributeException("加载现存分销用户错误：上级节点不匹配，部门上级节点" + upLevelNode.getId()+ "，节点上级" + distributeNodeRoleChain.getUpLevelNodeId());
        }
        distributeNodeRoleChainExistModel.setDistributeNodeRoleChain(distributeNodeRoleChain);

        return distributeNodeRoleChainExistModel;
    }

    /**
     * method : loadModelByUserId
     * description :分销体系用户的模型，必须有且只有一条生效的节点，角色，链记录,每次修改现存用户用这个方法加载，顺便检查用户链
     *
     * @param userId         \{@link Long \} 分销体系用户id
     * @param distributeType \{@link Integer \} 分销体系用户id
     * @return : cn.shengchao.examstar.distribute.model.DistributeNodeRoleChainExistModel
     * @author : Xiong weiqiang
     * @CreateDate : 2025-03-26 14:05:06
     *
     * @Reviewed :
     * @UpdateLog : Name Date Reason/Contents
     *            ---------------------------------------
     *            **** **** ****
     *
     */
    public DistributeNodeRoleChainExistModel loadModelByUserId(Long userId,
                                                               Integer distributeType) throws DistributeException {
        DistributeNodeRoleChainExistModel distributeNodeRoleChainExistModel = new DistributeNodeRoleChainExistModel();
        List<DistributeNodeInfo> userNodes = distributeNodeInfoService.list(Wrappers
            .lambdaQuery(DistributeNodeInfo.class)
            .eq(DistributeNodeInfo::getDistributeType, distributeType)
            .eq(DistributeNodeInfo::getUserId, userId)
            .eq(DistributeNodeInfo::getDataStatus, DistributeDataStatusEnum.STATUS_CURT.getStatus()));
        if (CollUtil.isNotEmpty(userNodes) && userNodes.size() > 1) {
            throw new DistributeException("加载现存分销用户错误：本人节点数量:" + userNodes.size());
        }
        //如果用户节点为空，返回空模型，不必再检查了
        if (CollUtil.isEmpty(userNodes)) {
            //返回空模型
            return distributeNodeRoleChainExistModel;
        }
        List<DistributeNodeRoleChain> nodeRoleChainList = distributeNodeRoleChainService.list(Wrappers
            .lambdaQuery(DistributeNodeRoleChain.class)
            .eq(DistributeNodeRoleChain::getDistributeNodeId, userNodes.getFirst().getId())
            .eq(DistributeNodeRoleChain::getDistributeType, distributeType)
            .eq(DistributeNodeRoleChain::getRefUserId, userId)
            .eq(DistributeNodeRoleChain::getDataStatus, DistributeDataStatusEnum.STATUS_CURT.getStatus()));
        if (CollUtil.isEmpty(nodeRoleChainList) && nodeRoleChainList.size() > 1) {
            throw new DistributeException("加载现存分销用户错误：本人链记录数量" + nodeRoleChainList.size());
        }
        DistributeNodeRole distributeNodeRole = distributeNodeRoleService.getById(userNodes.getFirst()
            .getDistributeUserRoleId());
        if (distributeNodeRole == null || DistributeDataStatusEnum.STATUS_CURT.getStatus() != distributeNodeRole
            .getDataStatus()) {
            throw new DistributeException("加载现存分销用户错误：本人角色数据缺失" + (CollUtil.isNotEmpty(userNodes)
                ? userNodes.size()
                : 0));
        }
        distributeNodeRoleChainExistModel.setDistributeNodeInfo(userNodes.getFirst());
        distributeNodeRoleChainExistModel.setDistributeNodeRole(distributeNodeRole);
        distributeNodeRoleChainExistModel.setDistributeNodeRoleChain(nodeRoleChainList.getFirst());
        Long upLevelNodeId = nodeRoleChainList.getFirst().getUpLevelNodeId();
        DistributeNodeInfo upLevelNode = null;
        //如果用户上级节点id为0，则上级节点为平台节点
        if (UserCs.PLATFORM_NODE_ID.equals(upLevelNodeId)) {
            //平台节点
            upLevelNode = DistributeNodeRoleChainCreator.buildPlatformNodeInfo();
        } else {
            upLevelNode = distributeNodeInfoService.getById(upLevelNodeId);
        }
        if (upLevelNode == null) {
            throw new DistributeException("加载现存分销用户错误：上级节点找不到" + upLevelNodeId);
        } else {
            distributeNodeRoleChainExistModel.setUpLevelNodeInfo(upLevelNode);
        }
        return distributeNodeRoleChainExistModel;
    }
}